package com.henry.lifegame;

public class GameOfLife {

    int[] data;
    int width;
    int height;

    public GameOfLife(int rows, int cols, int[] dataIn) {
        this.height = rows;
        this.width = cols;
        this.data = dataIn;
        for (int i = 0; i < data.length; i++) {
            if (i != 0) data[i] = 1;
        }
    }

    private int getValue(int row, int col) {
        // 处理越界
        row += height;
        row %= height;
        col += width;
        col %= width;
        return data[row * width + col];
    }

    private boolean getNextStatus(boolean living, int surrounding) {
        if (living) {
            return surrounding >= 2 && surrounding <= 3;
        } else {
            return surrounding == 3;
        }
    }

    private int[] getNext() {
        int[] nextData = new int[height * width];
        for (int i = 0; i < height; i++) { // row
            for (int j = 0; j < width; j++) { // column
                // count surrounding
                int countLiving = 0;

                countLiving += getValue(i - 1, j - 1);
                countLiving += getValue(i - 1, j + 0);
                countLiving += getValue(i - 1, j + 1);

                countLiving += getValue(i, j - 1);
                countLiving += getValue(i, j + 1);

                countLiving += getValue(i + 1, j - 1);
                countLiving += getValue(i + 1, j + 0);
                countLiving += getValue(i + 1, j + 1);

                nextData[i * height + j] = getNextStatus(getValue(i ,j) == 1, countLiving) ? 1 : 0;
            }
        }
        return nextData;
    }

    public void next() {
        this.data = this.getNext();
    }

    public int[] getData() { return data; }
}
